package main;

//Nikolas Wolfe
//2/9/2009
//CIS 4930
//Towers of Hanoi

/*
* Good AI... I think
*/

public class ConcreteSmartExecution implements ExecutionStrategy
{
	private TowerWatcher c;

	public ConcreteSmartExecution(TowerWatcher c)
	{
		this.c = c;
	}
	
	public void run()
	{
		while( !Thread.interrupted() )
		{
			try
			{
				// this will interrupt the thread if the puzzle has been solved
				if( legalMoveExists() && !c.getToh().checkIfSolved() )
				{
					// don't repeat previous moves from the right
					HanoiTower pt = c.getMyTower().peekTower().getPrevTower();
					HanoiTower rt = c.getMyTower().getRightTower();
					if( !pt.equals(rt) )
					{
						// since right is not our previous move, we can try that
						tryMoveRight();
					}
					
					// don't repeat previous moves from the left
					HanoiTower lt =  c.getMyTower().getLeftTower();
					if( !pt.equals(lt) )
					{
						tryMoveLeft();
					}
				}
				// yield if done
				c.checkToYieldAction();
				c.getToh().checkReadyToYield(c.getMyTower());
			} 
			catch( InterruptedException e )
			{
				// set the flag to exit the while loop
				// at the start of the next iteration
				Thread.currentThread().interrupt();
			}
		}
	}
	
	public boolean tryMoveLeft() throws InterruptedException
	{
		c.setActionCount(c.getActionCount()+1);
		return c.getToh().moveDiskLeft(c.getMyTower(), c.toString()); 
	}
	
	public boolean tryMoveRight() throws InterruptedException
	{
		c.setActionCount(c.getActionCount()+1);
		return c.getToh().moveDiskRight(c.getMyTower(), c.toString());
	}
	
	public boolean leftIsEmpty()
	{
		return c.getMyTower().getLeftTower().isEmpty();
	}
	
	public boolean rightIsEmpty()
	{
		return c.getMyTower().getRightTower().isEmpty();
	}
	
	public boolean legalMoveExists() throws InterruptedException
	{
		return c.getToh().hasLegalMove(c.getMyTower(), c.toString());
	}
}
